package com.maserb.monitor.web.schoolNotice;

import com.maserb.monitor.common.*;
import com.maserb.monitor.entity.JwOrgEntity;
import com.maserb.monitor.entity.JwRegistrationEntity;
import com.maserb.monitor.entity.SysCode;
import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.entity.schoolNotice.SchoolNoticeEntity;
import com.maserb.monitor.entity.schoolNotice.SchoolNoticeHistoryEntity;
import com.maserb.monitor.enums.SchoolNoticeTypeEnum;
import com.maserb.monitor.model.JwOrgTreeModel;
import com.maserb.monitor.model.SchoolNoticeSizeModel;
import com.maserb.monitor.model.SchoolNoticeSubjectModel;
import com.maserb.monitor.repository.schoolNotice.SchoolNoticeHistoryRepository;
import com.maserb.monitor.service.author_manage.UserService;
import com.maserb.monitor.service.base.IToolService;
import com.maserb.monitor.service.common.JwRegistrationService;
import com.maserb.monitor.service.jwEducation.JwOrgService;
import com.maserb.monitor.service.schoolNotice.SchoolNoticeHistoryService;
import com.maserb.monitor.service.schoolNotice.SchoolNoticeService;
import com.maserb.monitor.service.sysCode.SysCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 通知通告手机端
 */
@Controller
@RequestMapping("/notice")
public class SchoolNoticeController {


    @Autowired
    SchoolNoticeService schoolNoticeService;

    @Autowired
    IToolService toolService;

    @Autowired
    JwOrgService orgService;

    @Autowired
    UserService userService;

    @Autowired
    private SchoolNoticeHistoryRepository noticeHistoryRepository;

    @Autowired
    private SchoolNoticeHistoryService historyService;

    @Autowired
    private SysCodeService codeService;

    @Autowired
    private JwRegistrationService registrationService;

    /**
     * 获取通知公告列表
     * @param page
     * @param type
     * @param orgId
     * @param keyword
     * @return
     */
    @RequestMapping("/list")
    @ResponseBody
    public PageResponseResult<SchoolNoticeEntity> list(PageRequestParam page, final String type,final String orgId, final String keyword,final String userId) {
        Sort.Order codeOrder = new Sort.Order(Sort.Direction.DESC, "createTime");
        List<Sort.Order> orderList = new ArrayList<Sort.Order>();
        orderList.add(codeOrder);
        Sort sort = new Sort(orderList);
        return AjaxUtils.processPage(page,sort, new Func_T1<PageRequest, Page<SchoolNoticeEntity>>() {
            @Override
            public Page<SchoolNoticeEntity> invoke(PageRequest var1) throws Exception {
                Page<SchoolNoticeEntity> page = schoolNoticeService.findAll(var1,orgId, type, keyword);
                if(!StringUtils.isEmptyOrWhitespace(type)&&"1".equals(type)&&!StringUtils.isEmptyOrWhitespace(orgId)){
                    JwOrgEntity orgEntity = orgService.findOne(orgId);
                    if(null!=orgEntity && null!=orgEntity.getParent()){
                        if(orgEntity.getTreeLevel()==1){
                            page = schoolNoticeService.findAll(var1,orgEntity.getId(), type, keyword);
                        }else{
                            JwOrgEntity parentOrg = orgEntity.getParent();
                            page = schoolNoticeService.findAll(var1,parentOrg.getId(), type, keyword);
                        }
                    }
                }
                for(SchoolNoticeEntity entity : page.getContent()){
                    entity.setFmtCreateTime(toolService.formatYYMMDDHHMMSS(entity.getCreateTime()));
                    List<SchoolNoticeHistoryEntity> historyEntityList = noticeHistoryRepository.findByUserIdAndNoticeId(userId,entity.getId());
                    if(null!=historyEntityList && historyEntityList.size()>0){
                        SchoolNoticeHistoryEntity noticeHistoryEntity = historyEntityList.get(0);
                        if(null!=noticeHistoryEntity.getIsRead()){
                            entity.setIsRead(noticeHistoryEntity.getIsRead());
                        }
                    }
                    if(!StringUtils.isEmptyOrWhitespace(type)&&"4".equals(type)){
                        if(!StringUtils.isEmptyOrWhitespace(entity.getSubjectId())){
                            SysCode code = codeService.findOne(entity.getSubjectId());
                                if(null!=code){
                                    entity.setSubjectId(code.getName());
                                }

                        }
                    }
                }
                return page;
            }
        });
    }

    /**
     * 获取作业列表
     * @param type
     * @param orgId
     * @return
     */
    @RequestMapping("/operationList")
    @ResponseBody
    public List<SchoolNoticeSubjectModel> operationList( final String type, final String orgId,final String keyword,final String userId) {
        List<SysCode>codeList = codeService.findByParent("SCHOOL_COURSE");
        List<SchoolNoticeSubjectModel> modelList = new ArrayList<SchoolNoticeSubjectModel>();
        for(SysCode code :codeList){
            SchoolNoticeSubjectModel model = new SchoolNoticeSubjectModel();
            List<SchoolNoticeEntity> noticeList = schoolNoticeService.findAllBySubjectId(orgId, type, keyword,code.getId());
            if(null!=noticeList && noticeList.size()>0){
                for(SchoolNoticeEntity entity : noticeList){
                    entity.setFmtCreateTime(toolService.formatYYMMDDHHMMSS(entity.getCreateTime()));
                    List<SchoolNoticeHistoryEntity> historyEntityList = noticeHistoryRepository.findByUserIdAndNoticeId(orgId,userId);
                    if(null!=historyEntityList && historyEntityList.size()>0){
                        SchoolNoticeHistoryEntity noticeHistoryEntity = historyEntityList.get(0);
                        entity.setIsRead(noticeHistoryEntity.getIsRead());
                    }
                }
                model.setNoticeList(noticeList);
                model.setSubject(code);
                modelList.add(model);
            }
        }
        return modelList;
    }


    /**
     * 根据科目获取作业列表
     * @param page
     * @param type
     * @param orgId
     * @param keyword
     * @return
     */
    @RequestMapping("/operationNoticeList")
    @ResponseBody
    public PageResponseResult<SchoolNoticeEntity> operationNoticeList(PageRequestParam page, final String type,final String orgId, final String keyword,final String userId,String subjectId) {
        Sort.Order codeOrder = new Sort.Order(Sort.Direction.DESC, "createTime");
        List<Sort.Order> orderList = new ArrayList<Sort.Order>();
        orderList.add(codeOrder);
        Sort sort = new Sort(orderList);
        return AjaxUtils.processPage(page,sort, new Func_T1<PageRequest, Page<SchoolNoticeEntity>>() {
            @Override
            public Page<SchoolNoticeEntity> invoke(PageRequest var1) throws Exception {
                Page<SchoolNoticeEntity> page = schoolNoticeService.findAll(var1,orgId, type, keyword,subjectId);
                for(SchoolNoticeEntity entity : page.getContent()){
                    entity.setFmtCreateTime(toolService.formatYYMMDDHHMMSS(entity.getCreateTime()));
                    List<SchoolNoticeHistoryEntity> historyEntityList = noticeHistoryRepository.findByUserIdAndNoticeId(orgId,userId);
                    if(null!=historyEntityList && historyEntityList.size()>0){
                        SchoolNoticeHistoryEntity noticeHistoryEntity = historyEntityList.get(0);
                        entity.setIsRead(noticeHistoryEntity.getIsRead());
                    }
                }
                return page;
            }
        });
    }

    /**
     * 获取通知数量列表
     * @param orgId
     * 学校或班级id
     * @return
     */
    @RequestMapping("/sizeList")
    @ResponseBody
    public AjaxResult<List<SchoolNoticeSizeModel>> sizeList(final String orgId,final String userId) {
        return AjaxUtils.process(new Func_T<List<SchoolNoticeSizeModel>>() {
            @Override
            public List<SchoolNoticeSizeModel> invoke() throws Exception {
                SchoolNoticeTypeEnum[] enums = SchoolNoticeTypeEnum.values();
                List<SchoolNoticeSizeModel>modelList = new ArrayList<SchoolNoticeSizeModel>();
                for(SchoolNoticeTypeEnum noticeTypeEnum :enums){
                    SchoolNoticeSizeModel model = new SchoolNoticeSizeModel();
                    if(noticeTypeEnum.getValue()==1){
                        model.setType("1");
                        model.setName(SchoolNoticeTypeEnum.getNameByValue(1));
                        JwOrgEntity orgEntity = orgService.findOne(orgId);
                        JwOrgEntity prarenOrg = orgEntity.getParent();
                        int num1 = noticeHistoryRepository.countByOrgIdAndUserId(prarenOrg.getId(),userId,"1");
                        model.setScore(num1);
                    }else{
                        model.setType(noticeTypeEnum.getValue()+"");
                        model.setName(SchoolNoticeTypeEnum.getNameByValue(noticeTypeEnum.getValue()));
                        int num2 = noticeHistoryRepository.countByOrgIdAndUserId(orgId,userId,noticeTypeEnum.getValue()+"");
                        model.setScore(num2);
                    }
                    modelList.add(model);
                }
                return modelList;
            }
        });
    }

    /**
     * 显示学校通知条数
     * @param orgId
     * @param userId
     * @return
     */
    @RequestMapping("/noticeSize")
    @ResponseBody
    public AjaxResult<Integer> noticeSize(final String orgId,final String userId) {
        return AjaxUtils.process(new Func_T<Integer>() {
            @Override
            public Integer invoke() throws Exception {
                JwOrgEntity orgEntity = orgService.findOne(orgId);
                int num = 0;
                if(null!=orgEntity){
                    if(orgEntity.getTreeLevel()==1){
                        num = noticeHistoryRepository.countByOrgIdAndUserId(orgEntity.getId(),userId,"1");
                    }
                    else{
                        JwOrgEntity prarenOrg = orgEntity.getParent();
                        num = noticeHistoryRepository.countByOrgIdAndUserId(prarenOrg.getId(),userId,"1");
                    }
                }
                return num;
            }
        });
    }

    /**
     * 根据通知公告id获取详情
     * @param id
     * @return
     */
    @RequestMapping("/getNotice")
    @ResponseBody
    public AjaxResult<SchoolNoticeEntity> getNotice(final String id) {
        return AjaxUtils.process(new Func_T<SchoolNoticeEntity>() {
            @Override
            public SchoolNoticeEntity invoke() throws Exception {
                SchoolNoticeEntity entity = schoolNoticeService.findOne(id);
                if(null==entity){
                    return  null;
                }
                return entity;
            }
        });
    }

    /**
     * 科目列表
     * @return
     */
    @RequestMapping("/getSubjectType")
    @ResponseBody
    public AjaxResult<List<SysCode>> getSubjectType() {
        return AjaxUtils.process(new Func_T<List<SysCode>>() {
            @Override
            public List<SysCode> invoke() throws Exception {
                List<SysCode>codeList = codeService.findByParent("SCHOOL_COURSE");
                return codeList;
            }
        });
    }

    @RequestMapping("/add")
    @ResponseBody
    public AjaxResult<Boolean> add(final String title,final String type,final String content,final String orgId,final String userId,final String subjectId) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                SchoolNoticeEntity notice = new SchoolNoticeEntity();
                notice.setCreateTime(new Date());
                notice.setCreateUser(userId);
                notice.setSubjectId(subjectId);
                JwOrgEntity org = new JwOrgEntity();
                if(!StringUtils.isEmptyOrWhitespace(orgId)){
                    org = orgService.findOne(orgId);
                }
                notice.setOrg(org);
                notice.setTitle(title);
                notice.setContent(content);
                notice.setType(type);
                notice.setIsRead("0");
                schoolNoticeService.save(notice);
                return true;
            }
        });
    }

    /**
     * 标记已读
     * @param userId
     * @param noticeId
     * @return
     */
    @RequestMapping("/read")
    @ResponseBody
    public AjaxResult<Boolean> read(final String userId,final String noticeId) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                List<SchoolNoticeHistoryEntity> noticeHistoryEntities = noticeHistoryRepository.findByUserIdAndNoticeId(userId, noticeId);
                if(null!=noticeHistoryEntities&&noticeHistoryEntities.size()>0){
                    for(SchoolNoticeHistoryEntity historyEntity:noticeHistoryEntities){
                        //已读
                        historyEntity.setIsRead("1");
                        historyService.save(historyEntity);
                    }
                }
                return true;
            }
        });
    }

    /**
     * 根据登录用户返回用户学校及其管理的班级树
     * @param userId
     * @return
     */
    @RequestMapping("/getOrgListByUserId")
    @ResponseBody
    public List<JwOrgTreeModel> doOrgTreeByUser(String userId) {
        UserEntity user = userService.findOne(userId);
        JwOrgEntity jwOrgEntity = orgService.findOne(user.getOrgId());
        List<JwOrgTreeModel> modelList = new ArrayList<JwOrgTreeModel>();
        JwOrgTreeModel orgModel = new JwOrgTreeModel();
        List<JwOrgEntity>clazzList = orgService.findByUser(user);
        orgModel.setName(jwOrgEntity.getName());
        orgModel.setId(jwOrgEntity.getId());
        orgModel.setText(jwOrgEntity.getName());
        orgModel.setTreeLevel(jwOrgEntity.getTreeLevel());
        orgModel.setParentId(jwOrgEntity.getParent().getId());
        orgModel.setDescription(jwOrgEntity.getDescription());
        orgModel.setType(jwOrgEntity.getType());
        if(null!=clazzList && clazzList.size()>0){
            List<JwOrgTreeModel> modelList1 = new ArrayList<JwOrgTreeModel>();
            for(JwOrgEntity jwOrg:clazzList ){
                JwOrgTreeModel orgTreeModelClazz = new JwOrgTreeModel();
                orgTreeModelClazz.setName(jwOrg.getName());
                orgTreeModelClazz.setId(jwOrg.getId());
                orgTreeModelClazz.setText(jwOrg.getName());
                orgTreeModelClazz.setTreeLevel(jwOrg.getTreeLevel());
                orgTreeModelClazz.setParentId(jwOrg.getParent().getId());
                orgTreeModelClazz.setDescription(jwOrg.getDescription());
                orgTreeModelClazz.setType(jwOrg.getType());
                modelList1.add(orgTreeModelClazz);
            }
            orgModel.setChildren(modelList1);
            modelList.add(orgModel);
            return modelList;
        }
        return modelList;
    }

    //  启动程序后调用，保存uuid、registrationId（极光推送设备标识id），更新app使用时间;
    @RequestMapping("/doPush")
    @ResponseBody
    public AjaxResult doPush(String uuid,String registrationId) {
        return AjaxUtils.process(new Func_T<String>() {
            @Override
            public String invoke() throws Exception {
                JwRegistrationEntity entity = new JwRegistrationEntity();
                List<JwRegistrationEntity>list = registrationService.findByUuidAndRegistrationId(uuid,registrationId);
                if(null!=list&&list.size()>0){
                    entity = list.get(0);
                }else{
                    entity.setUuid(uuid);
                    entity.setRegistrationId(registrationId);
                    entity.setIsDel("0");
                }
                entity.setCreateTime(CreateTimeUtils.getCreateTime());
                registrationService.save(entity);
                return "success";
            }
        });
    }
}
